package fileProcessors.implementations;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fileProcessors.FileFormatException;
import fileProcessors.FileProcessor;

public class FrapConverter extends FileProcessor {

	public FrapConverter() {
		super("FrapConverter", ".txt", "_converted.txt");
	}

	@Override
	public void processFiles(File files[], File currentDirectory, File outputFile) throws FileFormatException {
		try {
			BufferedWriter bwResult = new BufferedWriter(new FileWriter(outputFile));
			for (int i = 0; i < files.length; i++) {
				bwResult.write("Loading "+files[i].getName()+".");
				bwResult.newLine();
				try {
					BufferedReader br = new BufferedReader(new FileReader(files[i]));
					BufferedWriter bw = new BufferedWriter(new FileWriter(new File("!"+files[i].getName().substring(0,
							files[i].getName().length() - 4)
							+ "_converted.txt")));
					
					/*
					 * Probeneigenschaften detektieren
					 */
					String name=files[i].getName();
					//Probe
					String sampleName =null;
					if(name.contains("HELA")){
						sampleName="Hela";
					}else{
						bwResult.write("WARNING: Sample not detected in filename "+name);
					}
					
					//Formname
					String shapeName=null;
					if(name.toUpperCase().contains("ARFGFP")){
						shapeName="ARF-GFP Golgi";
					}else if(name.toUpperCase().contains("ZYTO")){
						shapeName="Zytosol";
					}else{
						bwResult.write("WARNING: Shape not detected in filename "+name);
					}
					
					//Formgr��e
					String shapeSize=null;
			        Pattern p = Pattern.compile(".*?(\\d+).*"); //Question Mark (?) means reluctant matching
			        Matcher m = p.matcher(name);
			        ArrayList<Integer> intList=new ArrayList<Integer>();
			        if (m.matches()) {
			            do{
			                intList.add(Integer.parseInt(m.group(1)));
			            }while(m.find(m.end(1)));
			        }
			        intList.remove(0);
//					if(intList.size()>1){
//						shapeSize="";
//						for(int k=0; k<intList.size()-1;k++){
//							shapeSize+=intList.get(k)+" ";
//						}
//						shapeSize+="�m";
//					}else{
//						bwResult.write("WARNING: Size not detected in filename "+name);
//					}
					
//					//Bleaching
//					String bleachingNumbers=null;
//					if(intList.size()>0){
//						bleachingNumbers=""+intList.get(intList.size()-1);
//					}else{
//						bwResult.write("WARNING: Bleachingnumber not detected in filename "+name);
//					}
					
					//Header schreiben
					bw.write("t\tF(t)");
					bw.newLine();
					bw.write("s\tA.u.");
					bw.newLine();
					bw.write("Probe\t"+shapeName);
					bw.newLine();
//					bw.write("Form\t"+"Kreis");
//					bw.newLine();
//					bw.write("Gr��e\t"+"5 �m");
//					bw.newLine();
//					bw.write("Bleaching\t"+bleachingNumbers);
//					bw.newLine();
					
					
					//Dateiinhalt sortieren
					String line = br.readLine();
					boolean found = false;
					while (line != null) {
						char letzterChar = line.charAt(line.length() - 1);
						if (letzterChar == ',') {
							br.mark(1000); // Position mit Komma am Ende
											// markieren
							found = true;
						} else if (found && letzterChar != ',') {
							br.reset();
							br.readLine();
							break;
						}
						line = br.readLine();
						if (line == null && !found) {
							bwResult.write("Warning: End of Bleach not found in file " + files[i].getName());
						}
					}
					line=line.replace(",", "\t");
					String [] lineSplit=line.split("\t");
					double ersteZeit=Double.parseDouble(lineSplit[0]);
					while (line != null) {
						line = line.replace(",", "\t");
						lineSplit=line.split("\t");
						double zeit=Double.parseDouble(lineSplit[0]);
						zeit=zeit-ersteZeit;
						line=line.replace(lineSplit[0], ""+zeit);
						bw.write(line);
						bw.newLine();
						line=br.readLine();
						//Am ende Abshcneiden
//						if(zeit>15.){
//							break;
//						}
					}
					bw.close();
				} catch (FileNotFoundException e) {
					bwResult.write("ERROR: Could not read " + files[i].getName());
					bwResult.newLine();
				} catch (IOException e) {
					bwResult.write("ERROR during work in " + files[i].getName() + ":");
					bwResult.newLine();
					bwResult.write(e.getMessage());
					bwResult.newLine();
				}
				bwResult.write(files[i].getName()+" processed.");
				bwResult.newLine();
			}
			bwResult.close();
		} catch (IOException e1) {
			throw new FileFormatException("Fehler beim schreiben in Ergebnisdatei.");
		}
	}

	@Override
	public String getInformation() {
		return ("List alle Eingabedateien ein und sucht nach dem Ende der Bleach-Phase. Alle Zeilen "
				+ "ab dem Ende der BleachPhase werden anschlie�end in eine Ausgabedatei gleichen Namens geschrieben.");
	}

	@Override
	public String getDate() {
		return ("20.06.2013");
	}

}
